<template>
  <a-drawer
    :width="340"
    :mask-closable="false"
    :visible="visible"
    unmount-on-close
    :ok-loading="loading"
    @ok="onOk"
    @cancel="onCancel">
    <template #title>
      {{ title }}
    </template>
    <div>
      <a-form
        ref="form"
        layout="vertical"
        :model="form"
        :disabled="disabled"
        :style="{width:'100%'}"
      >
        <a-form-item
          field="username"
          :disabled="type !== Operation.CREATE"
          label="用户名:"
          :rules="[{required: true, message:'请输入用户名'}, {match: /^[a-zA-Z0-9_-]{4,16}$/, message: '4到16位（字母，数字，下划线，减号）'}]">
          <a-input v-model="form.username" placeholder="请输入用户名..." allow-clear />
        </a-form-item>
        <a-form-item
          field="nickname"
          label="昵称"
          :rules="[{maxLength: 16, message: '长度超限，最大16位'}]">
          <a-input v-model="form.nickname" placeholder="请输入昵称..." allow-clear />
        </a-form-item>
        <a-form-item
          field="password"
          label="密码"
          :rules="[{match:  /^[A-Za-z_][A-Za-z0-9_]{5,15}$/, message: '6到16位，只能包含大小写字母、数字和下划线，并且不能以数字开头'}]">
          <a-input v-model="form.password" type="password" placeholder="请输入密码..." allow-clear />
        </a-form-item>
        <a-form-item
          field="gender"
          label="性别"
        >
          <a-select
            v-model="form.gender"
            allow-clear
            placeholder="请选择性别..."
          >
            <a-option :value="1">男</a-option>
            <a-option :value="0">女</a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          field="phone"
          label="手机号"
          :rules="[{required: true, message:'请输入手机号'}, {match: /^(?:(?:\+|00)86)?1\d{10}$/, message: '手机号格式不正确'}]">
          <a-input v-model="form.phone" placeholder="请输入手机号..." allow-clear />
        </a-form-item>
        <a-form-item
          field="email" label="邮箱"
          :rules="[{match: /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/, message: '邮箱格式不正确'}]">
          <a-input v-model="form.email" placeholder="请输入邮箱..." allow-clear />
        </a-form-item>
        <a-form-item field="avatar" label="头像">
          <e-upload-image v-model:url="form.avatar" :width="100" :height="100" :show-file-list="false"/>
        </a-form-item>
        <a-form-item
          field="roles" label="角色">
          <a-select
            v-model="form.rolesId"
            multiple
            allow-clear
            direction="vertical"
            :allow-search="false"
            placeholder="请选择角色列表..."
          >
            <a-option v-for="role in roles" :key="role.code" :value="role.id">
              {{ role.name }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          field="depts" label="部门">
          <a-tree-select
            v-model="form.deptsId"
            multiple
            allow-clear
            :tree-checkable="true"
            :data="depts"
            :field-names="{
                key: 'id',
                title: 'name'
            }"
            tree-check-strictly
            placeholder="请选择组织机构..."
          ></a-tree-select>
        </a-form-item>
        <a-form-item field="enabled" label="状态">
          <a-switch
            v-model:model-value="form.enabled"
            type="round"
            :checked-value="true"
            :unchecked-value="false"
            unchecked-color="#F53F3F"
          >
            <template #checked>
              正常
            </template>
            <template #unchecked>
              异常
            </template>
          </a-switch>
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
</template>

<script>
import useLoading from "@/hooks/loading";
import {create, findById, update} from "@/api/modules/system/user";
import { listAll } from "@/api/modules/system/role";
import { listTree } from "@/api/modules/system/dept";
import { Operation } from "@/types/global";

const { loading, setLoading } = useLoading();

export default {
  name: 'UserBoard',
  emits: ['ok'],
  data() {
    return {
      visible: false,
      id: '',
      title: '',
      loading,
      form: {
        enabled: true
      },
      roles: [],
      depts: [],
      disabled: false,
      type: '',
      Operation
    }
  },
  methods: {
    async open(id, title, type) {
      if (id) {
        const { data: roles } = await listAll()
        this.roles = roles
        const { data: depts } = await listTree()
        this.depts = depts
        const { data } = await findById(id)
        this.form = {
          ...data,
          rolesId: data.roles.map(role => role.id),
          deptsId: data.depts.map(dept => dept.id)
        }
      }
      this.title = title
      this.type = type
      this.disabled = type === Operation.PREVIEW
      this.visible = true
    },
    close() {
      this.visible = false
      this.id = ''
      this.disabled = false
      this.type = ''
      this.form = {
        enabled: true
      }
      this.$refs.form.resetFields()
    },
    onOk() {
      if (this.type !== Operation.PREVIEW) {
        this.$refs.form.validate(async errors => {
          if (!errors) {
            try {
              setLoading(true)
              if (this.type === Operation.CREATE) {
                await create(this.form)
              } else {
                await update(this.form)
              }
              this.$emit('ok')
              this.close()
            } finally {
              setLoading(false)
            }
          }
        })
      } else {
        this.close()
      }
    },
    onCancel() {
      this.close()
    }
  }
}

</script>

<style scoped>

</style>
